<template>
  <div class="order-data-upload">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>订单数据管理</span>
          <el-button type="primary" @click="openUploadDialog">上传新图片</el-button>
        </div>
      </template>

      <!-- 筛选条件 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="filter-container">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="上传时间" prop="uploadTimeRange">
          <el-date-picker
            v-model="queryParams.uploadTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="图片类型" prop="imageType">
          <el-select v-model="queryParams.imageType" placeholder="请选择图片类型" clearable>
            <el-option v-for="item in imageTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 图片内容区域 -->
      <div v-loading="loading" class="image-container">
        <el-empty v-if="imageList.length === 0" description="暂无图片数据" />
        
        <el-row :gutter="20" v-else>
          <el-col v-for="(image, index) in imageList" :key="index" :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
            <el-card class="image-card" shadow="hover">
              <div class="image-wrapper">
                <el-image
                  :src="image.url"
                  :preview-src-list="[image.url]"
                  fit="cover"
                  class="data-image"
                  @click="previewImage(image)"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><PictureIcon /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
                <div class="image-info">
                  <div class="image-title" :title="image.name">{{ image.name }}</div>
                  <div class="image-meta">
                    <span>{{ image.orderNo }}</span>
                    <span>{{ image.uploadTime }}</span>
                  </div>
                  <div class="image-type">
                    <el-tag size="small" :type="getImageTypeTagType(image.type)">
                      {{ getImageTypeText(image.type) }}
                    </el-tag>
                  </div>
                </div>
                <div class="image-actions">
                  <el-button type="primary" link @click.stop="previewImage(image)">查看</el-button>
                  <el-button type="danger" link @click.stop="handleDelete(image)">删除</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 48, 96]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传订单数据图片" width="500px" :close-on-click-modal="false">
      <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules" label-width="80px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="uploadForm.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="图片类型" prop="imageType">
          <el-select v-model="uploadForm.imageType" placeholder="请选择图片类型" style="width: 100%">
            <el-option v-for="item in imageTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="图片描述" prop="description">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入图片描述（选填）"
          />
        </el-form-item>
        <el-form-item label="图片文件" prop="fileList">
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :data="uploadData"
            :multiple="true"
            :limit="10"
            :file-list="uploadForm.fileList"
            :on-exceed="handleExceed"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-progress="handleProgress"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            list-type="picture-card"
            accept=".jpg,.jpeg,.png,.gif"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                支持JPG/PNG/GIF格式，单个文件不超过5MB，最多可上传10张
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelUpload">取消</el-button>
          <el-button type="primary" :loading="uploading" @click="submitUpload">{{ uploading ? '上传中...' : '确认上传' }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="图片详情" width="800px">
      <div class="preview-container">
        <div class="preview-image">
          <el-image :src="currentImage.url" fit="contain" />
        </div>
        <div class="preview-info">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="图片名称">{{ currentImage.name }}</el-descriptions-item>
            <el-descriptions-item label="订单编号">{{ currentImage.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="图片类型">
              <el-tag :type="getImageTypeTagType(currentImage.type)">
                {{ getImageTypeText(currentImage.type) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="上传时间">{{ currentImage.uploadTime }}</el-descriptions-item>
            <el-descriptions-item label="图片大小">{{ formatFileSize(currentImage.size) }}</el-descriptions-item>
            <el-descriptions-item label="图片描述">{{ currentImage.description || '无' }}</el-descriptions-item>
          </el-descriptions>
          <div class="preview-actions">
            <el-button type="primary" @click="downloadImage(currentImage)">下载图片</el-button>
            <el-button type="danger" @click="handleDelete(currentImage)">删除图片</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, Plus } from '@element-plus/icons-vue'
import { formatDate } from '@/utils/index'

export default {
  name: 'OrderDataUpload',
  components: {
    PictureIcon: Picture,
    Plus
  },
  setup() {
    // 查询参数
    const queryParams = reactive({
      orderNo: '',
      uploadTimeRange: [],
      imageType: ''
    })

    // 数据列表
    const loading = ref(false)
    const imageList = ref([])
    const currentPage = ref(1)
    const pageSize = ref(12)
    const total = ref(0)

    // 上传对话框
    const uploadDialogVisible = ref(false)
    const uploadFormRef = ref(null)
    const uploading = ref(false)
    const uploadForm = reactive({
      orderNo: '',
      imageType: 'design',
      description: '',
      fileList: []
    })

    // 图片预览对话框
    const previewDialogVisible = ref(false)
    const currentImage = reactive({
      id: '',
      name: '',
      url: '',
      orderNo: '',
      type: '',
      uploadTime: '',
      size: 0,
      description: ''
    })

    // 选项数据
    const imageTypeOptions = [
      { value: 'design', label: '设计稿' },
      { value: 'material', label: '面料样品' },
      { value: 'pattern', label: '版型图' },
      { value: 'reference', label: '参考图' },
      { value: 'customer', label: '客户提供' },
      { value: 'other', label: '其他' }
    ]

    // 上传相关配置
    const uploadUrl = '/api/designer/order/upload'
    const uploadHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    const uploadData = reactive({
      orderNo: '',
      imageType: '',
      description: ''
    })

    // 表单验证规则
    const uploadRules = {
      orderNo: [
        { required: true, message: '请输入订单编号', trigger: 'blur' },
        { pattern: /^[A-Za-z0-9]+$/, message: '订单编号只能包含字母和数字', trigger: 'blur' }
      ],
      imageType: [
        { required: true, message: '请选择图片类型', trigger: 'change' }
      ],
      fileList: [
        { required: true, message: '请上传图片文件', trigger: 'change', type: 'array' }
      ]
    }

    // 获取图片列表
    const fetchImageList = () => {
      loading.value = true

      // 构建查询参数
      const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
        orderNo: queryParams.orderNo,
        imageType: queryParams.imageType
      }

      if (queryParams.uploadTimeRange && queryParams.uploadTimeRange.length === 2) {
        params.startDate = queryParams.uploadTimeRange[0]
        params.endDate = queryParams.uploadTimeRange[1]
      }

      // 这里应该调用API获取数据
      // 模拟数据
      setTimeout(() => {
        imageList.value = [
          {
            id: '1',
            name: '西装设计稿.jpg',
            url: '/uploads/orderData/design_1.jpg',
            orderNo: 'ORD20230001',
            type: 'design',
            uploadTime: '2023-05-10 14:30:00',
            size: 1024 * 1024 * 2.5, // 2.5MB
            description: '男士西装外套设计初稿'
          },
          {
            id: '2',
            name: '面料样品.jpg',
            url: '/uploads/orderData/material_1.jpg',
            orderNo: 'ORD20230001',
            type: 'material',
            uploadTime: '2023-05-10 15:20:00',
            size: 1024 * 1024 * 1.8, // 1.8MB
            description: '深蓝色羊毛面料样品'
          },
          {
            id: '3',
            name: '版型图.jpg',
            url: '/uploads/orderData/pattern_1.jpg',
            orderNo: 'ORD20230002',
            type: 'pattern',
            uploadTime: '2023-05-11 09:15:00',
            size: 1024 * 1024 * 3.2, // 3.2MB
            description: '女士连衣裙版型设计图'
          },
          {
            id: '4',
            name: '客户参考图.jpg',
            url: '/uploads/orderData/reference_1.jpg',
            orderNo: 'ORD20230002',
            type: 'reference',
            uploadTime: '2023-05-11 10:30:00',
            size: 1024 * 1024 * 1.5, // 1.5MB
            description: '客户提供的款式参考图'
          },
          {
            id: '5',
            name: '客户尺寸要求.jpg',
            url: '/uploads/orderData/customer_1.jpg',
            orderNo: 'ORD20230003',
            type: 'customer',
            uploadTime: '2023-05-12 16:45:00',
            size: 1024 * 1024 * 0.8, // 0.8MB
            description: '客户提供的尺寸要求'
          },
          {
            id: '6',
            name: '面料色卡.jpg',
            url: '/uploads/orderData/other_1.jpg',
            orderNo: 'ORD20230005',
            type: 'other',
            uploadTime: '2023-05-15 11:20:00',
            size: 1024 * 1024 * 1.2, // 1.2MB
            description: '颜色选择参考色卡'
          }
        ]
        total.value = 6
        loading.value = false
      }, 500)
    }

    // 查询方法
    const handleQuery = () => {
      currentPage.value = 1
      fetchImageList()
    }

    // 重置查询
    const resetQuery = () => {
      queryParams.orderNo = ''
      queryParams.uploadTimeRange = []
      queryParams.imageType = ''
      handleQuery()
    }

    // 页码变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchImageList()
    }

    // 当前页变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchImageList()
    }

    // 打开上传对话框
    const openUploadDialog = () => {
      resetUploadForm()
      uploadDialogVisible.value = true
    }

    // 重置上传表单
    const resetUploadForm = () => {
      if (uploadFormRef.value) {
        uploadFormRef.value.resetFields()
      }
      
      uploadForm.orderNo = ''
      uploadForm.imageType = 'design'
      uploadForm.description = ''
      uploadForm.fileList = []
    }

    // 取消上传
    const cancelUpload = () => {
      uploadDialogVisible.value = false
      resetUploadForm()
    }

    // 上传前检查
    const beforeUpload = (file) => {
      const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        ElMessage.error('只能上传JPG/PNG/GIF格式的图片!')
      }
      
      if (!isLt5M) {
        ElMessage.error('图片大小不能超过5MB!')
      }
      
      return isImage && isLt5M
    }

    // 超出数量限制
    const handleExceed = () => {
      ElMessage.warning('最多只能上传10张图片')
    }

    // 上传中
    const handleProgress = () => {
      uploading.value = true
    }

    // 上传成功
    const handleUploadSuccess = (res, file) => {
      ElMessage.success(`图片 ${file.name} 上传成功`)
    }

    // 上传失败
    const handleUploadError = (err, file) => {
      ElMessage.error(`图片 ${file.name} 上传失败：${err.message || '未知错误'}`)
    }

    // 移除文件
    const handleRemove = (file, fileList) => {
      uploadForm.fileList = fileList
    }

    // 提交上传
    const submitUpload = () => {
      uploadFormRef.value.validate((valid) => {
        if (valid) {
          if (uploadForm.fileList.length === 0) {
            ElMessage.warning('请至少上传一张图片')
            return
          }

          uploading.value = true
          
          // 更新上传时的附带数据
          uploadData.orderNo = uploadForm.orderNo
          uploadData.imageType = uploadForm.imageType
          uploadData.description = uploadForm.description

          if (uploadForm.fileList.length > 0 && uploadForm.fileList[0].status !== 'success') {
            // 如果有文件但未上传成功，手动上传
            ElMessage.info('正在处理未上传的文件...')
            // 等待上传完成后再关闭对话框
            setTimeout(() => {
              uploading.value = false
              uploadDialogVisible.value = false
              resetUploadForm()
              fetchImageList() // 刷新列表
            }, 1500)
          } else {
            // 所有文件都已上传成功
            ElMessage.success('图片上传成功')
            uploading.value = false
            uploadDialogVisible.value = false
            resetUploadForm()
            fetchImageList() // 刷新列表
          }
        }
      })
    }

    // 预览图片
    const previewImage = (image) => {
      Object.assign(currentImage, image)
      previewDialogVisible.value = true
    }

    // 下载图片
    const downloadImage = (image) => {
      // 创建下载链接
      const link = document.createElement('a')
      link.href = image.url
      link.download = image.name
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      ElMessage.success('开始下载图片')
    }

    // 删除图片
    const handleDelete = (image) => {
      ElMessageBox.confirm(`确定要删除图片"${image.name}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 这里应该调用API删除图片
        // 模拟删除成功
        ElMessage.success('图片删除成功')
        if (previewDialogVisible.value) {
          previewDialogVisible.value = false
        }
        fetchImageList() // 刷新列表
      }).catch(() => {})
    }

    // 格式化文件大小
    const formatFileSize = (size) => {
      if (size < 1024) {
        return size + ' B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB'
      } else if (size < 1024 * 1024 * 1024) {
        return (size / (1024 * 1024)).toFixed(2) + ' MB'
      } else {
        return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
      }
    }

    // 获取图片类型标签样式
    const getImageTypeTagType = (type) => {
      const typeMap = {
        design: 'success',
        material: 'warning',
        pattern: 'primary',
        reference: 'info',
        customer: 'danger',
        other: ''
      }
      return typeMap[type] || ''
    }

    // 获取图片类型文本
    const getImageTypeText = (type) => {
      const typeMap = {
        design: '设计稿',
        material: '面料样品',
        pattern: '版型图',
        reference: '参考图',
        customer: '客户提供',
        other: '其他'
      }
      return typeMap[type] || '未知'
    }

    onMounted(() => {
      fetchImageList()
    })

    return {
      // 数据
      queryParams,
      loading,
      imageList,
      currentPage,
      pageSize,
      total,
      imageTypeOptions,
      uploadDialogVisible,
      uploadFormRef,
      uploadForm,
      uploadRules,
      uploading,
      uploadUrl,
      uploadHeaders,
      uploadData,
      previewDialogVisible,
      currentImage,
      
      // 方法
      handleQuery,
      resetQuery,
      handleSizeChange,
      handleCurrentChange,
      openUploadDialog,
      cancelUpload,
      beforeUpload,
      handleExceed,
      handleProgress,
      handleUploadSuccess,
      handleUploadError,
      handleRemove,
      submitUpload,
      previewImage,
      downloadImage,
      handleDelete,
      formatFileSize,
      getImageTypeTagType,
      getImageTypeText
    }
  }
}
</script>

<style scoped>
.order-data-upload {
  padding: 10px;
}

.main-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
}

.image-container {
  min-height: 200px;
}

.image-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.image-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.image-wrapper {
  position: relative;
}

.data-image {
  width: 100%;
  height: 160px;
  border-radius: 4px 4px 0 0;
  cursor: pointer;
}

.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.image-error .el-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.image-info {
  padding: 10px;
}

.image-title {
  font-weight: bold;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.image-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.image-type {
  display: flex;
  justify-content: flex-end;
}

.image-actions {
  display: flex;
  justify-content: flex-end;
  padding: 5px 10px 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.image-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.image-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.preview-container {
  display: flex;
  gap: 20px;
}

.preview-image {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  max-height: 500px;
  overflow: hidden;
}

.preview-image .el-image {
  max-width: 100%;
  max-height: 500px;
}

.preview-info {
  flex: 1;
  min-width: 300px;
}

.preview-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 